

#import "SongViewController.h"
#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)
const NSInteger kStrings=6;
const NSInteger kMinMidiNote=40;
const NSInteger kMaxMidiNote=128;

@interface SongViewController ()
@property (weak, nonatomic) IBOutlet UISlider *speedSlider;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property NSInteger start;
@property (weak, nonatomic) IBOutlet UIButton *playButton;
@property (weak, nonatomic) IBOutlet UIButton *stopButton;
@property (weak, nonatomic) IBOutlet UIButton *dropBox;
@property SongsSingleton* songSingleton;
@property DBRestClient* restClient;
@property (weak, nonatomic) IBOutlet UIButton *mutedBut;

- (IBAction)recordPauseTapped:(id)sender;
- (IBAction)stopAudioRecordTapped:(id)sender;
-(IBAction)playTapped:(id)sender;
@property BOOL muted;

@property (weak, nonatomic) IBOutlet UIButton *backButton;

@property (weak, nonatomic) IBOutlet UIButton *RecordButton;
@property (weak, nonatomic) IBOutlet UIButton *StopAudioRecordButton;
@property (weak, nonatomic) IBOutlet UIButton *playAudioRecorder;

@property NSTimer* timer;
@end

AVAudioRecorder *recorder;
AVAudioPlayer *player;

@implementation SongViewController


#pragma mark - View

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.timer invalidate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    [self.tableView setOpaque:NO];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    
    //Initiate and set guitar notes
    self.guitarNotes=[[GuitarNotes alloc]init];
    self.songSingleton=[[SongsSingleton alloc]init];
    [self.guitarNotes songNotesFromCoreDataForSong:self.currentSong];
    self.soundBank=[[SoundBankPlayer alloc]init];
    [self.soundBank setSoundBank:@"Piano"];
    
    
    [self.StopAudioRecordButton setEnabled:NO];
    [self.playAudioRecorder setEnabled:NO];
    [self.stopButton setEnabled:NO];
    
    // Set the audio file
    NSArray *pathComponents = [NSArray arrayWithObjects:
                               [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
                               @"MyAudioMemo.m4a",
                               nil];
    NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
    
    // Setup audio session
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    
    // Define the recorder setting
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
    
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
    
    // Initiate and prepare the recorder
    recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL];
    recorder.delegate = self;
    recorder.meteringEnabled = YES;
    [recorder prepareToRecord];
    
    
    //table view
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    CGFloat rads = DEGREES_TO_RADIANS(-90);
    CGAffineTransform transform = CGAffineTransformRotate(CGAffineTransformIdentity, rads);
    self.tableView.transform = transform;
    [self.tableView registerNib:[UINib nibWithNibName:@"TableViewCell" bundle:nil] forCellReuseIdentifier:@"MyCell"];
    
    self.restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
    self.restClient.delegate = self;
    
    UIImage* backBut=[UIImage imageNamed:@"Back.png"];
    [self.backButton setImage:backBut forState:UIControlStateNormal];
    UIImage* playBut=[UIImage imageNamed:@"Play"];
    [self.playButton setImage:playBut forState:UIControlStateNormal];
    UIImage* stopBut=[UIImage imageNamed:@"Stop.png"];
    [self.stopButton setImage:stopBut forState:UIControlStateNormal];
    UIImage* recordBut=[UIImage imageNamed:@"Record.png"];
    [self.RecordButton setImage:recordBut forState:UIControlStateNormal];
    UIImage* stopRec=[UIImage imageNamed:@"StopRec.png"];
    [self.StopAudioRecordButton setImage:stopRec forState:UIControlStateNormal];
    UIImage* playRec=[UIImage imageNamed:@"PlayRec.png"];
    [self.playAudioRecorder setImage:playRec forState:UIControlStateNormal];
    UIImage* mute=[UIImage imageNamed:@"Mute-2.png"];
    [self.mutedBut setImage:mute forState:UIControlStateNormal];
    UIImage* dropBox=[UIImage imageNamed:@"DropBoxShare.png"];
    [self.dropBox setImage:dropBox forState:UIControlStateNormal];
    
}




#pragma mark -Buttons

- (IBAction)uploadToDropBox:(id)sender {
    if (![[DBSession sharedSession] isLinked]) {
        [[DBSession sharedSession] linkFromController:self];
    }
    
    NSString *filename = @"MyAudioMemo.m4a";
    NSString *localDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *localPath = [localDir stringByAppendingPathComponent:filename];
    
    
    // Upload file to Dropbox
    NSString *destDir = @"/";
    [self.restClient uploadFile:@"NewRecord.m4a" toPath:destDir withParentRev:nil fromPath:localPath];
    
    [[[UIAlertView alloc]initWithTitle:@"" message:@"Succesfully uploaded" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil]show];
}
- (IBAction)muteMusic:(id)sender {
    UIImage* mute;
    if(self.muted){
      mute=[UIImage imageNamed:@"Mute-2.png"];
    self.muted=NO;
    }
    else{
       mute =[UIImage imageNamed:@"Mute_Not.png"];
        self.muted=YES;
    }
   
    [self.mutedBut setImage:mute forState:UIControlStateNormal];
    [self.timer invalidate];
    
    if(!self.playButton.enabled){
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.speedSlider.value
                                                  target:self selector:@selector(moveSelectorToIndexPath) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
    
}

- (IBAction)backToAllSongs:(id)sender {
    [self.timer invalidate];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"toggle" object:nil];
    [[self presentingViewController] dismissViewControllerAnimated:YES completion:nil];
}


- (IBAction)stopButton:(id)sender {
    [self.playButton setEnabled:YES];
    [self.timer invalidate];
    [self.stopButton setEnabled:NO];
    
    
}
- (IBAction)play:(id)sender {
    
    [self.stopButton setEnabled:YES];
    [self.playButton setEnabled:NO];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.speedSlider.value target:self selector:@selector(moveSelectorToIndexPath) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

-(void)moveSelectorToIndexPath{
    NSInteger row = [[self.tableView indexPathForSelectedRow] row];
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:++row inSection:0] animated:NO scrollPosition:UITableViewScrollPositionMiddle];
    if(!self.muted){
    for(NSInteger line=0;line<kStrings;line++){
        NSInteger currNote=[self.guitarNotes currentNoteWithCharacter:[self.guitarNotes characterAtIndex:row forLine:line] forLine:line];
        if(currNote>=kMinMidiNote && currNote<kMaxMidiNote){
            [self.soundBank queueNote:(short)currNote gain:5.0f];
        }
    }
    [self.soundBank playQueuedNotes];
 }
    if(row==[self.guitarNotes numberOfCharacters]-1){
        [self.timer invalidate];
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionMiddle];
        [self.playButton setEnabled:YES];
        [self.stopButton setEnabled:NO];
        
    }
   

    
}




-(IBAction)recordPauseTapped:(id)sender{
    if (player.playing) {
        [player stop];
    }
    
    if (!recorder.recording) {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setActive:YES error:nil];
        
        // Start recording
        [recorder record];
        [self.RecordButton setTitle:@"Pause" forState:UIControlStateNormal];
        
    } else {
        
        // Pause recording
        [recorder pause];
        [self.RecordButton setTitle:@"Record" forState:UIControlStateNormal];
    }
    
    [self.StopAudioRecordButton setEnabled:YES];
    [self.playAudioRecorder setEnabled:NO];
}
-(IBAction)stopAudioRecordTapped:(id)sender{
    [recorder stop];
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setActive:NO error:nil];
    
    
}
- (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder successfully:(BOOL)flag{
    [self.RecordButton setTitle:@"Record" forState:UIControlStateNormal];
    
    [self.StopAudioRecordButton setEnabled:NO];
    [self.playAudioRecorder setEnabled:YES];
}
-(IBAction)playTapped:(id)sender{
    if (!recorder.recording){
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:recorder.url error:nil];
        [player setDelegate:self];
        [player play];
        
        
    }
}
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Done"
                                                    message: @"Finish playing the recording!"
                                                   delegate: nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}

-(void)viewWillAppear:(BOOL)animated{
    [self.speedSlider addTarget:self action:@selector(dragEndedForSlider)
               forControlEvents:UIControlEventTouchUpInside];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"toggle" object:nil];
}
-(void)dragEndedForSlider{
    [self.timer invalidate];
    if(!self.playButton.enabled){
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.speedSlider.value
    target:self selector:@selector(moveSelectorToIndexPath) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
}

#pragma mark - TableView

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.guitarNotes numberOfCharacters];
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString* articleCellId = @"MyCell";
    
    TableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:articleCellId forIndexPath:indexPath];
    
    CGFloat rads = DEGREES_TO_RADIANS(90);
    CGAffineTransform transform = CGAffineTransformRotate(CGAffineTransformIdentity, rads);
    
    for(UILabel* curr in cell.strings){
        curr.text=[self.guitarNotes characterAtIndex:indexPath.row forLine:[cell.strings indexOfObject:curr]];
        curr.transform=transform;
    }
    return cell;
}




@end
